package com.unknowpupil.sell.controller;

import com.google.common.collect.Lists;
import com.unknowpupil.sell.common.BasePage;
import com.unknowpupil.sell.common.request.Result;
import com.unknowpupil.sell.domain.ProductCategory;
import com.unknowpupil.sell.domain.ProductInfo;
import com.unknowpupil.sell.service.IProductCategoryService;
import com.unknowpupil.sell.service.IProductInfoService;
import com.unknowpupil.sell.vo.ProductInfoVo;
import com.unknowpupil.sell.vo.ProductVo;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表 前端控制器
 * </p>
 *
 * @author AutoGenerator
 */
@Api(tags = {"ProductInfo"}, description = "商品表模块")
@RestController
@RequestMapping(value = "/api/buyer/product/")
public class ProductInfoController {
    @Autowired
    private IProductInfoService productInfoService;
    @Autowired
    private IProductCategoryService productCategoryService;
    @GetMapping("list")
    public Result list(BasePage page){
        //得到所有商品
        List<ProductInfo> productInfos = productInfoService.list();
        //得到所有商品的类目id
        List<Integer> categories = productInfos.stream().map(e -> e.getCategoryType()).collect(Collectors.toList());
        //得到所有类目
        List<ProductCategory> categoryList = productCategoryService.findByCategoryTypeIn(categories);
        List<ProductVo> productVoList = Lists.newArrayList();
       //循环所有类目
        categoryList.forEach(category->{
            ProductVo productVo = new ProductVo();
            productVo.setCategoryName(category.getCategoryName());
            productVo.setCategoryType(category.getCategoryType());
            List<ProductInfoVo> productInfoVoList = Lists.newArrayList();
            //循环所有商品
            productInfos.forEach(product->{
                //比较所有商品的类别 进行类别封装
                if(product.getCategoryType().equals(category.getCategoryType())){
                    ProductInfoVo productInfoVo = new ProductInfoVo();
                    //spring提供的拷贝
                    BeanUtils.copyProperties(product,productInfoVo);
                    productInfoVoList.add(productInfoVo);
                }
            });
            //封装称，类别下面的所有商品
            productVo.setProductInfoVos(productInfoVoList);
            productVoList.add(productVo);
        });
        return  Result.ok(productVoList);
    }

}
